/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: JwtUtil.java
 * Author: YuXingZh
 * Date: 10/6/2024 上午12:11
 * Description:
 * Jwt工具类
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.g1.utils;

import com.bosssoft.g1.vo.RoleAuthVO;
import com.bosssoft.g1.vo.RoleVO;
import com.bosssoft.g1.vo.UserAuthVO;
import com.bosssoft.g1.vo.UserVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @className: JwtUtil
 * @description: 解决什么问题：
 * 演示线程池的正确使用
 * 主要方法和数据成员：
 * methodxx 使用 ThreadPoolExecutor创建线程进行任务操作
 * 注意事项：
 * 例如：该类需要从容器获取不可以new
 * @author: YuXingZh
 * @date: 10/6/2024上午12:11
 * @since 1.0
 **/
public class JwtUtil {
    private static final String SECRET_KEY = "your_secret_key";
    private static final long EXPIRATION_TIME = 86400000; // 1天

    public static String generateToken(UserAuthVO userVO) {
        return Jwts.builder()
                .setSubject(userVO.getCode())
                .claim("username", userVO.getName())
                .claim("orgId", userVO.getOrgId())
                .claim("companyId", userVO.getCompanyId())
                .claim("tenantId", userVO.getTenantId())
                .claim("roleList", userVO.getRoleList())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static UserAuthVO parseToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        String code = claims.getSubject();
        String username = claims.get("username", String.class);
        Long orgId = claims.get("orgId", Long.class);
        Long companyId = claims.get("companyId", Long.class);
        Long tenantId = claims.get("tenantId", Long.class);
        List<RoleAuthVO> roleList = claims.get("roleList", List.class);

        UserAuthVO userVO = new UserAuthVO();
        userVO.setCode(code);
        userVO.setName(username);
        userVO.setOrgId(orgId);
        userVO.setCompanyId(companyId);
        userVO.setTenantId(tenantId);
        userVO.setRoleList(roleList);

        return userVO;
    }

}
